package com.ygxsk.carhome.retrofit;

import java.io.File;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.ResponseBody;

/*
 * @Author:itchenqi
 * @Time:2022-10-30  12:57
 * @Description:下载文件相关
 */
public class DownloadApi {

    /**
     * @param url                  文件地址
     * @param destDir              存储文件夹
     * @param fileName             存储文件名
     * @param fileDownLoadObserver 监听回调
     */
    public static void downloadFile(@NonNull String url, final String destDir, final String fileName, final FileDownloadObserver<File> fileDownLoadObserver) {

        NetworkManager.getInstance()
                .initRetrofitRxJava()
                .create(ApiService.class)
                .downloadFileWithUrlSync(url)//下载地址内容
                .subscribeOn(Schedulers.io())//subscribeOn和ObserOn必须在io线程，如果在主线程会出错
                .observeOn(Schedulers.io())
                .observeOn(Schedulers.computation())//需要Schedulers.computation() -用于诸如事件循环和回调处理之类的计算工作；
                .map(new Function<ResponseBody, File>() {
                    @Override
                    public File apply(ResponseBody responseBody) throws Exception {
                        //return fileDownLoadObserver.saveFile(responseBody, destDir, fileName);
                        //FileUtils.createFileByDeleteOldFile(destDir+File.separator+fileName);
                        // TODO: 2022-10-30 13:23  这里存储文件将来可以再次优化,例如 加载进度；
                        return fileDownLoadObserver.saveFile(responseBody, destDir, fileName);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fileDownLoadObserver);

    }
}

